var BASE_URL = 'http://jinzhidata.com/v2'

//读取cookie
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)) {
        return unescape(arr[2]);
    }
    return null;
}

function uploadResource() {
    if (!getCookie("accessToken")) {
        alert("您还没有登录")
        return;
    }
    var formData = new FormData(document.getElementById("resourceForm"))
    formData.append("resourceDetail", editor.txt.html())
    if (!formData.get('resourceName')) {
        alert('请填写资源名称！')
        return
    }
    if (!formData.get('resourcePrice')) {
        alert('请填写资源积分！')
        return
    }
    if (!formData.get('resourceTypeId')) {
        alert('请填写资源类型！')
        return
    }
    if (!formData.get('resoureFile').name) {
        alert("请上传资源文件！");
        return
    }
    var coverImageName = formData.get('coverImage').name
    if (coverImageName && !/.(jpeg|jpg|png)$/.test(coverImageName)) {
        alert("资源封面图片类型必须是jpeg,jpg,png中的一种");
        return
    }
    var loading = layer.load(1, {
        shade: [0.1, '#fff'],
        // content: '上传中......'
    });
    $.ajax({
        type: "post",
        url: BASE_URL + "/resource",
        data: formData,
        contentType: false,
        processData: false,
        success: function (res) {
            layer.close(loading);
            if (res.code === 0) {
                alert('上传成功!')
                location.href = BASE_URL
            } else if (res.code === 1001) {
                alert("您还没有登录！")
                location.href = BASE_URL + "/user.html"
            } else {
                alert(res.msg)
            }
        }
    })
}

$(function () {
    // 加载分类
    $.ajax({
        url: BASE_URL + "/resource/type/list",
        type: "get",
        contentType: 'application/json',
        dataType: "json",
        success: function (response) {
            var data = response.data
            for (var i = 0; i < data.length; i++) {
                var resourceTypeId = data[i].resourceTypeId
                var resourceTypeName = data[i].resourceTypeName
                $("select[name='resourceTypeId']").append('<option value="' + resourceTypeId + '">' + resourceTypeName + '</option>')
            }
        }
    })
})